<template>
  <div class="body" v-loading="loading">
    <el-form ref="form" size="small" :model="form" label-width="100px">
      <el-row>
        <el-col :span="6">
          <el-form-item label="调拨单号" prop="billNo">
            {{ form.billNo }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="调拨类型" prop="allocationType">
            {{ getAllocationTypeName(form.allocationType) }}
          </el-form-item>
        </el-col>
        <el-col :span="6" style="text-align: right">
          <el-button type="success" size="small" icon="el-icon-check" @click="saveAllocation" v-if="!form.status">&nbsp;保&nbsp;存&nbsp;</el-button>
          <el-button type="primary" size="small" icon="el-icon-s-promotion" @click="auditAllocation" v-else-if="form.status === 'save'">&nbsp;审&nbsp;核&nbsp;</el-button>
          <el-button type="warning" size="small" icon="el-icon-s-promotion" @click="unauditAllocation" v-else-if="form.status === 'audit'">&nbsp;反&nbsp;审&nbsp;</el-button>
          <el-button type="info" size="small" @click="gotoList()" icon="el-icon-back">返 回</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="创建人员" prop="createUserName">
            {{ form.createUserName }}
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="创建时间" prop="createTime">
            {{ form.createTime }}
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="审核人员" prop="auditUserName">
            {{ form.auditUserName }}
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="审核时间" prop="auditTime">
            {{ form.auditTime }}
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="仓库" prop="stockNo">
            <el-select v-model="form.stockNo" clearable :disabled="form.status === 'audit'" placeholder="请选择仓库" @change="getLocation(form.stockNo)" size="small">
              <el-option v-for="item in stockList" :key="item.key" :label="item.name" :value="item.key"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="仓位" prop="locationNo">
            <el-select v-model="form.locationNo" :disabled="form.status === 'audit'" clearable placeholder="请选择仓位" size="small">
              <el-option v-for="item in locationList" :key="item.locationNo" :label="item.locationName" :value="item.locationNo"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="调拨仓库" prop="toStockNo">
            <el-select v-model="form.toStockNo" clearable :disabled="form.status === 'audit'" placeholder="请选择仓库" @change="getToLocation(form.toStockNo)" size="small">
              <el-option v-for="item in toStockList" :key="item.key" :label="item.name" :value="item.key"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="调拨仓位" prop="toLocationNo">
            <el-select v-model="form.toLocationNo" clearable :disabled="form.status === 'audit'" placeholder="请选择仓位" @change="saveAllDetail(form.toLocationNo)" size="small">
              <el-option v-for="item in toLocationList" :key="item.locationNo" :label="item.locationName" :value="item.locationNo"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" :disabled="form.status === 'audit'" :rows="2" placeholder="请输入备注" style="width: 310px"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-button style="margin-left: 20px; margin-top: -10px" v-if="form.status !== 'audit'" type="success" @click="this.show = true" size="small">新增物料</el-button>
        </el-col>
      </el-row>
    </el-form>

    <el-dialog title="添加物料" v-model="show" v-loading="materialListLoading" center width="1000px" top="70px" :append-to-body="true" :close-on-press-escape="true" :close-on-click-modal="false">
      <el-row>
        <el-col :span="6" class="number">
          <span>仓库</span>
          <el-input style="margin-right: 20px" v-model="this.form.stockNo" disabled size="small"></el-input>
        </el-col>
        <el-col :span="6" class="number">
          <span>仓位</span>
          <el-input v-model="this.form.locationNo" disabled size="small"></el-input>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="9" class="col">
          <span style="margin-right: -5px">物料</span>
          <el-select style="width: 285px" filterable remote size="small" :remote-method="e => getMaterialStockList(e)" v-model="this.materialNo" clearable class="material" placeholder="请输入物料编码或者名称">
            <el-option v-for="item in this.materialList" :key="item.fNumber" :label="item.fNumber + '：' + item.fName + ' ' + item.fSpecification" :value="item.fNumber" />
          </el-select>
        </el-col>
        <el-col :span="6" class="col">
          <span style="margin-left: -15px">批次</span>
          <el-input style="width: 180px; margin-left: -10px" v-model="this.batchNo" size="small" clearable></el-input>
        </el-col>
        <el-col :span="6" class="col">
          <span style="margin-left: -10px">箱号</span>
          <el-input style="width: 180px; margin-left: -10px" v-model="this.boxNo" size="small" clearable></el-input>
        </el-col>
        <el-col :span="3">
          <el-button size="small" @click="getMaterial()">搜索</el-button>
        </el-col>
      </el-row>
      <el-table :data="dataList" class="detail" height="60vh" @selection-change="handleSelectionChange">
        <el-table-column type="selection"></el-table-column>
        <el-table-column label="#" width="40" align="center" type="index"></el-table-column>
        <el-table-column prop="materialNo" label="物料编码"></el-table-column>
        <el-table-column prop="materialName" label="物料名称"></el-table-column>
        <el-table-column prop="materialSpec" label="物料规格"></el-table-column>
        <el-table-column prop="batchNo" label="批次"></el-table-column>
        <el-table-column prop="count" label="重量" align="right" width="60"></el-table-column>
        <el-table-column prop="boxNo" label="箱号" width="180"></el-table-column>
      </el-table>
      <div style="display: flex; justify-content: center; margin-top: 10px">
        <el-button type="success" @click="dataToMaterial">添加</el-button>
        <el-button @click="show = false" type="info">关闭</el-button>
      </div>
    </el-dialog>

    <el-table :data="materialList" style="width: 100%" height="60%">
      <el-table-column label="No." width="60" align="right" type="index"></el-table-column>
      <el-table-column prop="materialName" label="物料名称" min-width="180px"></el-table-column>
      <el-table-column prop="materialNo" label="物料编码" min-width="150px"></el-table-column>
      <el-table-column prop="materialSpec" label="规格" min-width="130px"></el-table-column>
      <el-table-column prop="batchNo" label="批次" min-width="120px"></el-table-column>
      <el-table-column prop="boxCount" label="箱数" min-width="80px" align="right"></el-table-column>
      <el-table-column prop="count" label="总重" min-width="80px" align="right">
        <template #default="scope">
          {{ scope.row.count? Number(scope.row.count.toFixed(6)): scope.row.count }}
        </template>
      </el-table-column>
      <el-table-column prop="stockNo" label="仓库" min-width="180px">
        <template #default="scope">
          {{ scope.row.stockNo + ':' + getStockName(scope.row.stockNo) }}
        </template>
      </el-table-column>
      <el-table-column prop="locationNo" label="仓位" width="80px"></el-table-column>
      <el-table-column label="调拨至仓库" width="160px">
        <template #default="scope">
          <el-select v-model="scope.row.toStockNo" clearable :disabled="this.form.status === 'audit'" placeholder="请选择仓库" @change="detailGetLocation(scope.row)" size="small">
            <el-option v-for="item in toStockList" :key="item.key" :label="item.name" :value="item.key"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="调拨至仓位" width="160px">
        <template #default="scope">
          <el-select v-model="scope.row.toLocationNo" clearable :disabled="this.form.status === 'audit'" placeholder="请选择仓位" size="small">
            <el-option v-for="item in toLocationList" :key="item.locationNo" :label="item.locationName" :value="item.locationNo"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="200px" align="left" fixed="right">
        <template #default="scope">
          <el-button type="text" style="color: #67c23a" icon="el-icon-check" @click="saveDetail(scope.row)" v-if="form.status !== 'audit'">保存</el-button>
          <el-button type="text" style="color: #409EFF" icon="el-icon-view" @click="getMaterialBoxList(scope.row.id)">查看</el-button>
          <el-button type="text" style="color: var(--el-color-danger)" icon="el-icon-delete" @click="deleteMaterial(scope.row.id)" v-if="form.status !== 'audit'">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-table :data="materialBoxList" style="width: 100%" height="calc(100vh - 580px)">
      <el-table-column label="No." width="60" align="right" type="index"></el-table-column>
      <el-table-column prop="stockNo" label="仓库" min-width="180px">
        <template #default="scope">
          {{ scope.row.stockNo + ':' + getStockName(scope.row.stockNo) }}
        </template>
      </el-table-column>
      <el-table-column prop="locationNo" label="仓位" min-width="80px"></el-table-column>
      <el-table-column prop="materialNo" label="物料编码" min-width="150px"></el-table-column>
      <el-table-column prop="materialName" label="物料名称" min-width="150px"></el-table-column>
      <el-table-column prop="materialSpec" label="规格" min-width="120px"></el-table-column>
      <el-table-column prop="batchNo" label="批次" min-width="120px"></el-table-column>
      <el-table-column prop="count" label="重量" min-width="80px" align="right"></el-table-column>
      <el-table-column prop="boxNo" label="箱号" min-width="150px"></el-table-column>
      <el-table-column label="操作" width="80px" align="center" fixed="right" v-if="form.status ==='save'">
        <template #default="scope">
          <el-button type="text" style="color: var(--el-color-danger)" icon="el-icon-delete" @click="deleteMaterialBox(scope.row.id, scope.row.detailId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { getBoxNo } from '../../utils'
import {ElMessage} from "element-plus";

export default {
  data() {
    return {
      loading: false,
      materialListLoading: false,
      dataList:[],
      show: false,
      detailShow: false,
      allocationShow: false,
      drawer: false,
      type: 'boxNo',
      input: '',
      stockNo: '',
      locationNo: '',
      toStockNo: '',
      toLocationNo: '',
      stockList: [],
      toStockList: [],
      locationList: [],
      toLocationList: [],
      materialList: [],
      materialBoxList: [],
      direction: 'rtl',
      form: {},
      materialNo: '',
      batchNo: '',
      boxNo: '',
      multipleSelection: [],
      header: {},
      allocationTypeList: []
    }
  },
  async mounted() {
    this.loading = true
    try {
      await this.getStock()
      await this.getAllocationType()
      let billNo = this.$route.query.billNo
      if (billNo) {
        await this.getBill(billNo)
      } else {
        await this.getMaterialList()
      }
    } finally {
      this.loading = false
    }

  },
  methods: {
    async getBill(billNo) {
      let res = await this.callApi('get_allocation_web_detail', { billNo, allocationType: 'pda' })
      if (res.res) {
        this.materialList = res.data
        this.form = res.header
      }
    },
    async auditAllocation() {
      this.loading = true
      try {
        const res = await this.callApi('audit_user_allocation', { billNo: this.form.billNo })
        if (!res.res) return
        ElMessage.success("审核成功")
      } finally {
        this.loading = false
      }
    },
    async unauditAllocation() {
      this.loading = true
      try {
        const res = await this.callApi('unaudit_user_allocation', {
          billNo: this.form.billNo,
          allocationType: 'pda'
        })
        if (!res.res) return
        ElMessage.success("反审成功")
      } finally {
        this.loading = false
      }
    },
    gotoList() {
      return this.$router.push('/allocation/pdaAllocationList')
    },
    async dataToMaterial() {
      if (this.multipleSelection.length === 0) {
        ElMessage.error('请选择物料！')
        return
      }
      this.show = false
      await this.addMaterialBox(this.multipleSelection)
      await this.getMaterialList()
    },
    closeDetail() {
      this.detailShow = false;
      this.dataList = [];
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /**
     * 从即时库存里获取箱子
     */
    async getMaterial() {
      this.materialListLoading = true
      try {
        const res = await this.callApi('get_material_box_from_stock', {
          materialNo: this.materialNo,
          batchNo: this.batchNo,
          boxNo: this.boxNo,
          stockNo: this.form.stockNo,
          locationNo: this.form.locationNo
        })
        if (!res.res) return
        this.dataList = res.data
        if (this.dataList.length === 0) {
          ElMessage.warning('未查询到符合条件的物料!')
        }
      } finally {
        this.materialListLoading = false
      }
    },
    /**
     * 获取物料
     */
    async getMaterialStockList(val) {
      if (!val) {
        this.materialList = []
        return
      }
      this.materialLoading = true
      try {
        const res = await this.callApi('get_material_by_key', {key: val, pageSize: 20})
        if (!res.res) return
        this.materialList = res.data
      } finally {
        this.materialLoading = false
      }
    },
    /**
     * 获取状态名
     */
    getStockName(val) {
      if (this.stockList && this.stockList.length > 0) {
        for (let i = 0; i < this.stockList.length; i++) {
          if (this.stockList[i].key === val) {
            return this.stockList[i].name;
          }
        }
      }
      return '';
    },
    /**
     * 获取状态名
     */
    getAllocationTypeName(val) {
      if (this.allocationTypeList && this.allocationTypeList.length > 0) {
        for (let i = 0; i < this.allocationTypeList.length; i++) {
          if (this.allocationTypeList[i].key === val) {
            return this.allocationTypeList[i].name;
          }
        }
      }
      return '';
    },
    async getBoxDetail(input) {
      this.loading = true
      try {
        let res
        if (this.type === 'boxNo') {
          res = await this.callApi('get_user_allocation_box_list', {
            boxNo: input,
            stockNo: this.stockNo,
            locationNo: this.locationNo
          })
        } else {
          let rfid = input.split("\n");
          res = await this.callApi('get_user_allocation_rfid', {rfid: rfid})
        }
        if (!res) return
        if (this.type === 'boxNo') {
          this.dataList.push(res)
        } else {
          this.dataList = res.data
        }

        this.detailShow = true
      } finally {
        this.loading = false
      }
    },
    async getStock() {
      let res = await this.$api.getChildDictionaryListByKeys({
        keys: ['stock']
      });
      if (!res.res) return;
      this.stockList = res.stock;
      this.toStockList = res.stock;
    },
    async getAllocationType() {
      let res = await this.$api.getChildDictionaryListByKeys({
        keys: ['allocationType']
      });
      if (!res.res) return;
      this.allocationTypeList = res.allocationType;
    },
    async getLocation(stockNo) {
      if (!stockNo) {
        this.form.locationNo = '';
        this.locationList = [];
        return
      }
      let res = await this.callApi('get_locationNo', {stockNo: stockNo});
      if (!res.res) return;
      this.form.locationNo = '';
      this.locationList = res.data;
    },
    async getToLocation(stockNo) {
      if (!stockNo) {
        this.form.toLocationNo = '';
        this.toLocationList = [];
        return
      }
      this.materialList.forEach((option) => {
        option.toStockNo = stockNo
      })
      let res = await this.callApi('get_locationNo', {stockNo: stockNo});
      if (!res.res) return;
      this.form.toLocationNo = '';
      this.toLocationList = res.data;
    },
    async detailGetLocation(row) {
      let res = await this.callApi('get_locationNo', {stockNo: row.toStockNo});
      if (!res.res) return;
      this.toLocationList = res.data;
      row.toLocationNo = ''
    },
    async getAllocationLocation() {
      this.loading = true;
      try {
        let res = await this.callApi('get_locationNo', {stockNo: this.toStockNo});
        if (!res.res) return;
        this.locationList = res.data;
        this.locationNo = '';
      } finally {
        this.loading = false;
      }
    },
    async addMaterialBox(multipleSelection) {
      this.loading = true;
      try {
        let detailList = []
        multipleSelection.forEach(value => {
          detailList.push({
            stockNo: value.stockNo,
            locationNo: value.locationNo,
            boxNo: value.boxNo,
            materialNo: value.materialNo,
            materialName: value.materialName,
            materialSpec: value.materialSpec,
            batchNo: value.batchNo,
            unit: value.unit,
            count: value.count,
            exp: value.exp,
            produceDate: value.produceDate,
            rfid: value.rfid,
            allocationType: 'pda'
          })
        })
        let res = await this.callApi('add_user_allocation_box_list', {boxList: detailList})
        if (!res) return;
        this.detailShow = false;
        this.show = false;
        await this.getMaterialList()
        this.dataList = []
      } finally {
        this.loading = false;
      }
    },
    async getMaterialList() {
      this.loading = true;
      try {
        let res = await this.callApi('get_user_material');
        if (!res.res) return;
        this.materialList = res.data;
      } finally {
        this.loading = false;
      }
    },
    async saveDetail(row) {
      let res = await this.callApi('update_allocation', {
        id: row.id,
        toStockNo: row.toStockNo,
        toLocationNo: row.toLocationNo
      });
      if (!res.res) return;
      ElMessage.success("保存成功")
    },
    async saveAllDetail(locationNo) {
      this.materialList.forEach((option) => {
        option.toLocationNo = locationNo
      })
      let res = await this.callApi('update_all_allocation', {
        toStockNo: this.form.toStockNo,
        toLocationNo: this.form.toLocationNo,
        allocationType: 'pda'
      });
      if (!res.res) return;
    },
    async getMaterialBoxList(id) {
      this.loading = true;
      try {
        let res = await this.callApi('get_user_material_box', { detailId: id });
        if (!res.res) return;
        this.materialBoxList = res.data;
      } finally {
        this.loading = false;
      }
    },
    async deleteMaterial(id) {
      try {
        await this.$confirm(`确定删除物料吗`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        return
      }
      this.loading = true;
      try {
        let res = await this.callApi('delete_material_allocation', {id: id});
        if (!res.res) return;
        await this.getMaterialList()
      } finally {
        this.loading = false;
      }
    },
    async deleteMaterialBox(id, detailId) {
      this.loading = true;
      try {
        let res = await this.callApi('delete_box_allocation', {id: id});
        if (!res.res) return;
        if (this.materialBoxList.length === 1) {
          await this.getMaterialList()
        } else {
          await this.getMaterialBoxList(detailId)
        }
      } finally {
        this.loading = false;
      }
    },
    async saveAllocation() {
      try {
        await this.$confirm(`确定调拨仓库吗`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        return
      }
      this.loading = true;
      try {
        let res = await this.callApi('save_user_allocation', {
          stockNo: this.form.stockNo,
          locationNo: this.form.locationNo,
          toStockNo: this.form.toStockNo,
          toLocationNo: this.form.toLocationNo,
          allocationType: 'web',
          remark: this.form.remark
        });
        if (!res.res) return;
        let billNo = res.billNo
        await this.getBill(billNo)
      } finally {
        this.loading = false;
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.body {
  padding: 20px 0;
  display: flex;
  height: calc(100vh - 70px);
  flex-direction: column;
  :deep(.el-form){
    flex: 0;
    flex-shrink: 0;
  }
  :deep(.el-table){
    flex: 1;
  }
}
.bottom {
  display: flex;
  padding-top: 20px;
  justify-content: center;
}
.col {
  display: flex;
  span {
    width: 40px;
    line-height: 35px;
    font-size: 14px;
    margin-right: 10px;
  }
}
.number {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  span {
    width: 46px;

  }

}
</style>
